import axios from 'axios'
import Vue from 'vue'
import store from '../vuex/store'
import router from '../router/index'
import {
  Message
} from 'view-design'

Vue.prototype.prefix = process.env.PRE_FIX
Vue.prototype.baseUrl = process.env.API_ROOT

window._axiosPromiseArr = []

axios.defaults.timeout = 600000

let _this = this

Vue.prototype.$http = (url = '', data = {}, type = 'get', callback) => {
  axios({
    headers: {
      "Content-Type": "application/json;charset=UTF-8",
    },
    method: type,
    baseURL: process.env.API_ROOT,
    url: url,
    data: JSON.stringify(data),
    params: type.toLowerCase() === 'get' ? data : {}
  }).then((res) => {
    callback && callback(res)
  }).catch((error) => {
    if (error.message == 'cancel') {
      return false
    }
    // Message.error('请求超时')
  })
}

axios.interceptors.request.use(config => {
  config.headers.common['token'] = store.state.token || localStorage.getItem('token') || ''
  config.cancelToken = new axios.CancelToken(function (cancel) {
    store.commit('pushToken', { cancelToken: cancel })
  })
  return config
}, error => {
  return Promise.reject(error)
})

axios.interceptors.response.use(response => {
  if (response.data) {
    switch (response.data.code) {
      case 401:
        localStorage.clear()
        router.replace({
          path: '/'
        })
      // 2001 未登录 
      case 2001:
        localStorage.clear()
        router.replace({
          path: '/'
        })
    }
  }
  return response
}, error => {
  return Promise.reject(error)
})